package nl.gamayun.whohasit;

import java.util.Calendar;
import java.util.List;

import nl.gamayun.whohasit.utils.WhoHasItUtils;
import nl.gamayun.whohasit.widgets.DateSlider.DateSlider;
import nl.gamayun.whohasit.widgets.DateSlider.DefaultDateSlider;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

public class LoanActivity extends Activity implements OnTouchListener
{

	static final private String	TAG						= LoanActivity.class.getSimpleName();
	static final int ACITIVITY = 0;
	static final int DATESELECTOR_ID = 0;
	static final int RETURNDATESELECTOR_ID = 1;

	private WhoHasItHandler whoHasItHandler;
	private TextView title;
	private EditText header;
	private Spinner types;
	private EditText loanerName;
	private EditText detail;
	private TextView loanReturnDate;
	private ImageButton returnDateButton;
	private TextView loanDate;
	private ImageButton dateButton;
	private ImageButton contactButton;
	
	private Loan selectedLoan;

	private Intent contactIntent;
	private Contact contact;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loan);
		whoHasItHandler = WhoHasItUtils.getWhoHasItHandler(this);
		contactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
		contactButton = (ImageButton) findViewById(R.id.loanContactButton);
		contactButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
            	startActivityForResult(contactIntent, 1);            
            }
        });
		if (this.getPackageManager().queryIntentActivities(contactIntent, PackageManager.MATCH_DEFAULT_ONLY).size() == 0)
		{
			contactButton.setVisibility(ImageButton.INVISIBLE);
		}

		Bundle bundle = getIntent().getExtras();
		Log.d(TAG, "bundle:"+getIntent().getExtras());
		long loanId =bundle.getLong(Loan.LOAN_KEY, 0l);
		if (loanId == 0)
		{
			initializeSelectedLoan();
		}
		else
		{
			selectedLoan = whoHasItHandler.getLoan(loanId);
		}

		// get view items
		title = (TextView) findViewById(R.id.loanTitle);
		header = (EditText) findViewById(R.id.loanHeader);
		types = (Spinner) findViewById(R.id.loanType);
		ArrayAdapter<TYPE> adapter = new ArrayAdapter<TYPE>(getApplicationContext(),
				android.R.layout.simple_spinner_item, TYPE.values());
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		types.setAdapter(adapter);
		loanerName = (EditText) findViewById(R.id.loanLoanerName);
		detail = (EditText) findViewById(R.id.loanDetail);
		loanReturnDate = (TextView) findViewById(R.id.loanReturnDate);
		returnDateButton = (ImageButton) findViewById(R.id.loanReturnDateButton);
		returnDateButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                // call the internal showDialog method using the predefined ID
                showDialog(RETURNDATESELECTOR_ID);
            }
        });
		loanDate = (TextView) findViewById(R.id.loanDate);
		dateButton = (ImageButton) findViewById(R.id.loanDateButton);
		dateButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                // call the internal showDialog method using the predefined ID
                showDialog(DATESELECTOR_ID);
            }
        });

		Button okButton = (Button) findViewById(R.id.okButton);
		okButton.setText(R.string.button_ok);
		okButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				List<String> errors = selectedLoan.isValid(); 
				if (errors == null || errors.size() == 0)
				{
					saveLoan();
					LoanActivity.this.finish();
				}
				else
				{
					StringBuffer sb = new StringBuffer();
					for (int i=0; i < errors.size(); i++)
					{
						sb.append(errors.get(i));
						if (i+1<errors.size())
						{
							sb.append("\n");
						}
					}
					AlertMessage(getString(R.string.title_error), sb.toString());
				}
			}
		});

		Button cancelButton = (Button) findViewById(R.id.cancelButton);
		cancelButton.setText(R.string.button_cancel);
		cancelButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				LoanActivity.this.finish();
			}
		});

	}

	public boolean onTouch(View v, MotionEvent event)
	{
		Log.d(TAG, "onTouch");
		return false;
	}

	@Override
	protected void onPause()
	{
		Log.d(TAG, "onPause");
		super.onPause();
	}

	@Override
	protected void onResume()
	{
		Log.d(TAG, "onResume");
		super.onResume();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		Log.d(TAG, "onWindowFocusChanged");
		if (hasFocus)
			updateUIFromLoan();
		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	public void onDestroy()
	{
		whoHasItHandler.onDestroy();
		super.onDestroy();
	}
	
	private void initializeSelectedLoan() 
	{
		Log.d(TAG, "initializeSelectedLoan");
		Calendar returnDate = WhoHasItUtils.getDefaultReturnDate();
		selectedLoan = new Loan(returnDate);
	}

	private void updateUIFromLoan() 
	{
		Log.d(TAG, "updateUIFromLoan");

		title.setText(selectedLoan.getLoanID() == 0 ? R.string.title_new : R.string.title_update);
		header.setText(selectedLoan.getHeader());
		header.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// Do nothing
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// Do nothing
			}
			
			public void afterTextChanged(Editable s) {
				selectedLoan.setHeader(s.toString());
			}
		});
		
		types.setSelection(selectedLoan.getType().getType());
		types.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				Log.d(TAG, "Spinner TYPES onItemSelected");
				TYPE type = TYPE.getTypeByValue(parent.getItemAtPosition(pos).toString());
				selectedLoan.setType(type);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				Log.d(TAG, "Spinner TYPES onNothingSelected");
				selectedLoan.setType(TYPE.lent_from);
			}
		});

		loanerName.setText(selectedLoan.getLoanerName());
		loanerName.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// Do nothing
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// Do nothing
			}
			
			public void afterTextChanged(Editable s) {
				selectedLoan.setLoanerName(s.toString());
			}
		});
		
		detail.setText(selectedLoan.getDetail());
		detail.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// Do nothing
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// Do nothing
			}
			
			public void afterTextChanged(Editable s) {
				selectedLoan.setDetail(s.toString());
			}
		});

		loanReturnDate.setText( WhoHasItUtils.LOAN_DATE_FORMAT.format(selectedLoan.getReturnDate().getTime() ) );
		
		loanDate.setText( WhoHasItUtils.LOAN_DATE_FORMAT.format(selectedLoan.getDate().getTime() ) );
	}

	private void saveLoan() 
	{
		Log.d(TAG, "saveLoan");
		
		if (contact != null)
		{
			selectedLoan.setContactId(contact.getContactID());
		}
		if (selectedLoan.getLoanID() > 0)
		{
			whoHasItHandler.updateLoan(selectedLoan);
		}
		else
		{
			whoHasItHandler.addLoan(selectedLoan);
		}

	}
	
	
	
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.d(TAG, "onCreateOptionsMenu");
		super.onCreateOptionsMenu(menu);
		// Create and add new menu items.
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.loan_menu, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.d(TAG, "onOptionsItemSelected");
		super.onOptionsItemSelected(item);
		switch (item.getItemId())
		{
			case (R.id.menu_delete):
			{
				whoHasItHandler.removeLoan(selectedLoan);
				LoanActivity.this.finish();
				return true;
			}
		}
		return false;
	}

	@Override
    protected Dialog onCreateDialog(int id) {

        // this method is called after invoking 'showDialog' for the first time
        // here we initiate the corresponding DateSlideSelector and return the dialog to its caller
    	
        switch (id) {
        case DATESELECTOR_ID:
            return new DefaultDateSlider(this,dateSelectListener,selectedLoan.getDate());
        case RETURNDATESELECTOR_ID:
        	return new DefaultDateSlider(this,returndateSelectListener,selectedLoan.getReturnDate());
        }
        return null;
    }

    // define the listener which is called once a user selected the date.
    private DateSlider.OnDateSetListener dateSelectListener =
        new DateSlider.OnDateSetListener() {
            public void onDateSet(DateSlider view, Calendar selectedDate) {
                selectedLoan.setDate(selectedDate);
        		TextView loanDate = (TextView) findViewById(R.id.loanDate);
        		loanDate.setText( WhoHasItUtils.LOAN_DATE_FORMAT.format(selectedLoan.getDate().getTime() ) );
            }
    };

    // define the listener which is called once a user selected the date.
    private DateSlider.OnDateSetListener returndateSelectListener =
        new DateSlider.OnDateSetListener() {
            public void onDateSet(DateSlider view, Calendar selectedDate) {
                selectedLoan.setReturnDate(selectedDate);
        		TextView loanReturnDate = (TextView) findViewById(R.id.loanReturnDate);
        		loanReturnDate.setText( WhoHasItUtils.LOAN_DATE_FORMAT.format(selectedLoan.getReturnDate().getTime() ) );
        		
            }
    };

    public void AlertMessage( String title, String message )
    {
        new AlertDialog.Builder(this)
        .setTitle( title )
        .setMessage( message )
        .setNegativeButton(R.string.button_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                //Just close
            }
        }).show();
    }
    
    @Override  
    public void onActivityResult(int reqCode, int resultCode, Intent data) {  
        super.onActivityResult(reqCode, resultCode, data);  
        if (resultCode == Activity.RESULT_OK) {  
            Uri contactData = data.getData();
            Cursor c =  managedQuery(contactData, null, null, null, null);  
            if (c.moveToFirst()) {
            	Integer id = c.getInt(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                loanerName.setText(name);
                selectedLoan.setContactId(id);
                contact = new Contact(id, name);
            }  
        }  
    }

}
